import { createRouter, createWebHistory } from 'vue-router'
import { isLoggedIn, checkLoginStatus, getToken, clearToken } from '../api/auth.js'
import { getDictionary } from '../api/dictionary.js'
import { isDictionaryLoaded } from '../utils/dictionary.js'

// 懒加载组件
const Login = () => import('../components/Login.vue')
const MainLayout = () => import('../layouts/MainLayout.vue')
const Home = () => import('../components/Home.vue')
const Sites = () => import('../components/Sites.vue')
const Ranking = () => import('../components/Ranking.vue')
const Orders = () => import('../components/Orders.vue')
const Mine = () => import('../components/Mine.vue')
const Withdraw = () => import('../components/Withdraw.vue')
const IncomeRecords = () => import('../components/IncomeRecords.vue')
const WithdrawRecords = () => import('../components/WithdrawRecords.vue')
const ChangePassword = () => import('../components/ChangePassword.vue')

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: Login,
    meta: { requiresAuth: false }
  },
  {
    path: '/',
    component: MainLayout,
    meta: { requiresAuth: true },
    children: [
      {
        path: '',
        redirect: '/home'
      },
      {
        path: 'home',
        name: 'Home',
        component: Home
      },
      {
        path: 'sites',
        name: 'Sites',
        component: Sites
      },
      {
        path: 'ranking',
        name: 'Ranking',
        component: Ranking
      },
      {
        path: 'orders',
        name: 'Orders',
        component: Orders
      },
      {
        path: 'mine',
        name: 'Mine',
        component: Mine
      },
      {
        path: 'withdraw',
        name: 'Withdraw',
        component: Withdraw
      },
      {
        path: 'income-records',
        name: 'IncomeRecords',
        component: IncomeRecords
      },
      {
        path: 'withdraw-records',
        name: 'WithdrawRecords',
        component: WithdrawRecords
      },
      {
        path: 'change-password',
        name: 'ChangePassword',
        component: ChangePassword
      }
    ]
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫 - 登录验证
router.beforeEach(async (to, from, next) => {
  console.log('路由守卫执行，目标路径:', to.path, '来源路径:', from.path)
  
  // 检查是否有token
  const hasToken = getToken()
  console.log('当前token状态:', hasToken ? '有token' : '无token')
  
  // 处理根路径重定向
  if (to.path === '/') {
    console.log('访问根路径，跳转到首页')
    next('/home')
    return
  }
  
  // 如果访问登录页
  if (to.path === '/login') {
    if (hasToken) {
      // 有token但访问登录页，跳转到首页
      console.log('已登录但访问登录页，跳转到首页')
      next('/home')
      return
    } else {
      // 无token访问登录页，允许访问
      console.log('允许访问登录页')
      next()
      return
    }
  }
  
  // 检查页面是否需要认证
  if (to.meta.requiresAuth) {
    if (hasToken) {
      // 有token，允许访问
      console.log('有token，允许访问需要认证的页面')
      isLoggedIn.value = true
      
      // 检查并加载字典数据
      if (!isDictionaryLoaded()) {
        console.log('字典数据未加载，开始加载字典数据...')
        try {
          const dictResult = await getDictionary()
          if (dictResult.success) {
            // 将字典数据保存到本地存储
            localStorage.setItem('h5_dictionary', JSON.stringify(dictResult.data))
            console.log('字典数据加载成功')
          } else {
            console.warn('字典数据加载失败:', dictResult.message)
          }
        } catch (dictError) {
          console.error('加载字典数据异常:', dictError)
        }
      } else {
        console.log('字典数据已加载')
      }
      
      next()
      return
    } else {
      // 无token但需要认证，跳转到登录页
      console.log('需要登录但无token，跳转到登录页')
      isLoggedIn.value = false
      next('/login')
      return
    }
  }
  
  // 其他情况允许访问
  console.log('允许访问路径:', to.path)
  next()
})

export default router